<template>
  <div class="container">
    <div class="query">
      <el-form ref="formRef" :model="form" label-width="120px" label-suffix=":" inline>
        <!-- <div class="query_row"> -->
        <!-- 查询条件：姓名 -->
        <el-form-item prop="entityName">
          <el-input v-model="form.entityName" :placeholder="$t('entity.list_query_entityName')" />
        </el-form-item>
        <!-- 查询条件：个人类型 -->
        <el-form-item prop="identity">
          <el-select v-model="form.identity" :placeholder="$t('entity.list_query_identity')">
            <el-option :label="$t('entity.list_query_identity_all')" :value="0" />
            <el-option :label="$t('entity.list_query_identity_legal')" :value="1" />
            <el-option :label="$t('entity.list_query_identity_physics')" :value="2" />
          </el-select>
        </el-form-item>
        <!-- </div> -->
        <!-- 查询条件：实体类型 -->
        <el-form-item prop="entityType">
          <el-select
            v-model="form.entityType"
            multiple
            :placeholder="$t('entity.list_query_entityType')"
            collapse-tags
            collapse-tags-tooltip
            @change="entityTypeChange"
          >
            <el-option
              v-for="item in Object.keys(entityTypeEnum)"
              :key="item"
              :label="entityTypeEnum[item]"
              :value="parseInt(item)"
            />
          </el-select>
        </el-form-item>
        <!-- <div class="query_row"> -->
        <!-- 查询条件：文件类型 -->
        <el-form-item prop="documentType">
          <el-select
            v-model="form.documentType"
            multiple
            :placeholder="$t('entity.list_query_documentType')"
            collapse-tags
            collapse-tags-tooltip
            @change="documentTypeChange"
          >
            <el-option
              v-for="item in Object.keys(documentTypeEnum)"
              :key="item"
              :label="documentTypeEnum[item]"
              :value="parseInt(item)"
            />
          </el-select>
        </el-form-item>
        <!-- 查询条件：状态 -->
        <el-form-item prop="entityStatus">
          <el-select v-model="form.entityStatus" :placeholder="$t('entity.list_query_entityStatus')">
            <el-option :label="$t('entity.list_query_entityStatus_all')" :value="0" />
            <el-option :label="$t('entity.list_query_entityStatus_registered')" :value="2" />
            <el-option :label="$t('entity.list_query_entityStatus_pending')" :value="1" />
          </el-select>
        </el-form-item>
        <!-- </div> -->
        <!-- <div class="query_row"> -->
        <!-- 查询条件：交易名称 -->
        <el-form-item prop="tradeName">
          <el-input v-model="form.tradeName" :placeholder="$t('entity.list_query_tradeName')" />
        </el-form-item>
        <!-- 查询条件：创建时间 -->
        <el-form-item class="picker_item" prop="createTime">
          <el-date-picker
            v-model="form.createTime"
            type="datetimerange"
            :start-placeholder="$t('entity.list_query_createTime_start')"
            :end-placeholder="$t('entity.list_query_createTime_end')"
            format="DD-MM-YYYY HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <!-- 查询条件：查询按钮&重置按钮 -->
        <el-form-item class="query_reset">
          <el-button type="primary" @click="submitForm(formRef)">{{ $t('entity.list_query_searchBtn') }}</el-button>
          <el-button :disabled="resetDisable" @click="resetForm(formRef)">{{
            $t('entity.list_query_clearBtn')
          }}</el-button>
        </el-form-item>
        <!-- </div> -->
      </el-form>
    </div>
    <div class="list">
      <div class="list_operate">
        <el-button type="primary" @click="addEntity">{{ $t('entity.list_operate_add') }}</el-button>
        <el-button class="list_operate_print" @click="printEntityList">{{ $t('entity.list_operate_print') }}</el-button>
      </div>
      <!-- <div class="list_status">
        <div class="list_status_pending">
          <div class="list_status_pending_icon"></div>
          {{ $t('entity.list_query_entityStatus_pending') }}
        </div>
        <div class="list_status_registered">
          <div class="list_status_registered_icon"></div>
          {{ $t('entity.list_query_entityStatus_registered') }}
        </div>
      </div> -->
      <el-table
        :data="entityList"
        :default-sort="{ prop: 'date', order: 'descending' }"
        header-row-class-name="table_header"
        style="width: 100%"
        :header-cell-style="{
          backgroundColor: '#F6F8F7',
        }"
        @sort-change="tableSortChange"
      >
        <el-table-column prop="entityName" :label="$t('entity.list_table_header_entityName')" sortable min-width="24%">
          <template #default="scope">
            <router-link
              :to="scope.row.entityStatus === 2 ? '/entityManage?id=' + scope.row.id : '/entityEdit?id=' + scope.row.id"
            >
              {{ scope.row.entityName || '-' }}
            </router-link>
          </template>
        </el-table-column>
        <el-table-column prop="documentType" :label="$t('entity.list_table_header_documentType')" min-width="15%" />
        <el-table-column prop="tradeName" :label="$t('entity.list_table_header_tradeName')" min-width="15%" />
        <el-table-column prop="entityType" :label="$t('entity.list_table_header_entityType')" min-width="15%" />
        <el-table-column prop="entityStatus" :label="$t('entity.list_table_header_entityStatus')" min-width="15%">
          <template #default="scope">
            <div v-if="scope.row.entityStatus === 2" class="registered_icon">
              {{ $t('entity.list_query_entityStatus_registered') }}
            </div>
            <div v-if="scope.row.entityStatus === 1" class="pending_icon">
              {{ $t('entity.list_query_entityStatus_pending') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          :label="$t('entity.list_table_header_createTime')"
          :formatter="formatter"
          min-width="16%"
          sortable
        />
      </el-table>
      <div v-if="pageCount" class="list_pagination">
        <el-pagination
          v-model:currentPage="pageParams.page"
          v-model:page-size="pageParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageCount"
          @size-change="currentPageSizeChange"
          @current-change="currentPageChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue';
import router from '@/router';
import { useI18n } from 'vue-i18n';
import { ElLoading } from 'element-plus';
import type { FormInstance } from 'element-plus';
import loadsh from 'lodash';
import entityApi from '@/apis/entity';

const { t } = useI18n();
interface Entity {
  entityName: string;
  documentType: string;
  tradeName: string;
  entityType: string;
  entityStatus: string;
  createTime: string;
} // 列表item
// 文件号类型映射 后端需要存数字
const documentTypeEnum: any = computed(() => {
  return {
    0: t('entity.list_query_documentType_all'),
    301: t('entity.list_query_documentType_cnpj'),
    302: t('entity.list_query_documentType_nif'),
    303: t('entity.list_query_documentType_cpf'),
    304: t('entity.list_query_documentType_rne'),
    305: t('entity.list_query_documentType_rnm'),
  };
});
// 实体类型映射 后端需要存数字
const entityTypeEnum: any = computed(() => {
  return {
    0: t('entity.list_query_entityType_all'),
    101: t('entity.list_query_entityType_supplier'),
    102: t('entity.list_query_entityType_franchised'),
    103: t('entity.list_query_entityType_lawyer'),
    104: t('entity.list_query_entityType_complainant'),
    105: t('entity.list_query_entityType_defendant'),
    106: t('entity.list_query_entityType_granted'),
    107: t('entity.list_query_entityType_grantor'),
    108: t('entity.list_query_entityType_groupCompany'),
  };
});
const formRef = ref<FormInstance>();
// 初始表单，用于计算clear按钮是否禁用
const initialForm: any = reactive({
  entityName: '',
  identity: '',
  entityType: [],
  documentType: [],
  entityStatus: '',
  tradeName: '',
  createTime: ['', ''],
});
// 填的表单
const form: any = reactive({
  entityName: '',
  identity: '',
  entityType: [],
  documentType: [],
  entityStatus: '',
  tradeName: '',
  createTime: ['', ''],
});
// 其他参数
const pageParams = reactive({
  page: 1,
  pageSize: 10,
  orderField: '',
  isAsc: '',
});
const entityList: any = ref([]);
const pageCount = ref(0);
const resetDisable: any = computed(() => {
  return loadsh.isEqual(initialForm, form);
});
// 点击表格排序
const tableSortChange = (e: any) => {
  (pageParams.isAsc as any) = e.order === 'ascending' ? true : e.order === 'descending' ? false : '';
  pageParams.orderField = e.order === null ? '' : e.prop;
  getEntityList();
};
// 当前页改变
const currentPageChange = () => {
  getEntityList();
};
const currentPageSizeChange = () => {
  getEntityList();
};
// 格式化时间
const formatter = (row: Entity) => {
  return row.createTime;
};
// 跳转新增页
const addEntity = () => {
  router.push({
    path: '/entityAdd',
  });
};
// 导出实体列表
const printEntityList = () => {
  // 提前处理参数
  const formParams: any = loadsh.cloneDeep(form);
  formParams.startTime =
    (form.createTime && form.createTime[0] && form.createTime[0].toLocaleString().replace(/[/]/g, '-')) || '';
  formParams.endTime =
    (form.createTime && form.createTime[1] && form.createTime[1].toLocaleString().replace(/[/]/g, '-')) || '';
  formParams.entityType =
    form.entityType.includes(0) || form.entityType.length === 0
      ? Object.keys(entityTypeEnum.value)
          .slice(1, entityTypeEnum.value.length)
          .map((v) => parseInt(v))
      : form.entityType;
  formParams.documentType =
    form.documentType.includes(0) || form.documentType.length === 0
      ? Object.keys(documentTypeEnum.value)
          .slice(1, documentTypeEnum.value.length)
          .map((v) => parseInt(v))
      : form.documentType;
  delete formParams.createTime;
  // 正式请求
  const loading = ElLoading.service({
    lock: true,
    text: 'loading',
  });
  entityApi
    .getEntityExport(Object.assign({}, formParams, pageParams))
    .then((res) => {
      if (res.data) {
        let blob = new Blob([res.data], {
          type: 'application/vnd.ms-excel',
        });
        let date = new Date();
        let newTime =
          date.getFullYear() +
          '-' +
          (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) +
          '-' +
          date.getDate();
        let fileName = 'Entidade de legal' + newTime + '.xlsx';
        // @ts-ignore
        if (window.navigator.msSaveOrOpenBlob) {
          // @ts-ignore
          navigator.msSaveBlob(blob, fileName);
        } else {
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          link.click();
          // 释放内存
          window.URL.revokeObjectURL(link.href);
        }
      }

      loading.close();
    })
    .catch(() => {
      loading.close();
    });
  // const headers = {
  //   ACCESS_TOKEN: (store.state as any).user.token || '',
  //   'Client-Locale': i18n.locale.value || 'en-US',
  //   'System-Type': 'LEGAL',
  //   'Client-Type': 'WEB',
  // };
  // superagent
  //   .get('http://192.168.23.107:8086/lpas/law/entity/export/list')
  //   .query(Object.assign({}, formParams, pageParams))
  //   .set('Content-Type', 'bolb')
  //   .set(headers)
  //   .then((res: any) => {
  //     var link = document.createElement('a');
  //     link.href = res.req.url;
  //     link.click();
  //     // 释放内存
  //     loading.close();
  //   })
  //   .catch(() => {
  //     loading.close();
  //   });
};
// 当筛选条件实体类型改变
const entityTypeChange = (value: Array<string | number>) => {
  // 如果最后一项是all
  if (value.length && value.indexOf(0) === value.length - 1) {
    form.entityType = [0];
    return;
  }
  // 如果all已经在里面了
  if (value.includes(0)) {
    form.entityType.splice(value.indexOf(0), 1);
    return;
  }
};

// 当筛选条件文件类型改变
const documentTypeChange = (value: Array<string | number>) => {
  // 如果最后一项是all
  if (value.length && value.indexOf(0) === value.length - 1) {
    form.documentType = [0];
    return;
  }
  // 如果all已经在里面了
  if (value.includes(0)) {
    form.documentType.splice(value.indexOf(0), 1);
    return;
  }
};

// 查询按钮
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  getEntityList();
};

// 重置筛选条件
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  getEntityList();
};

// 获取实体列表方法
const getEntityList = () => {
  // 提前处理参数
  const formParams: any = loadsh.cloneDeep(form);
  formParams.startTime =
    (form.createTime && form.createTime[0] && form.createTime[0].toLocaleString().replace(/[/]/g, '-')) || '';
  formParams.endTime =
    (form.createTime && form.createTime[1] && form.createTime[1].toLocaleString().replace(/[/]/g, '-')) || '';
  formParams.entityType =
    form.entityType.includes(0) || form.entityType.length === 0
      ? Object.keys(entityTypeEnum.value)
          .slice(1, entityTypeEnum.value.length)
          .map((v) => parseInt(v))
      : form.entityType;
  formParams.documentType =
    form.documentType.includes(0) || form.documentType.length === 0
      ? Object.keys(documentTypeEnum.value)
          .slice(1, documentTypeEnum.value.length)
          .map((v) => parseInt(v))
      : form.documentType;
  delete formParams.createTime;
  // 正式请求
  const loading = ElLoading.service({
    lock: true,
    text: 'loading',
  });
  entityApi
    .getEntityList(Object.assign({}, formParams, pageParams))
    .then((res) => {
      if (!!res && res.data && res.code === 200) {
        entityList.value = res.data.records;
        pageCount.value = res.data.total;

        res.data.records.map(
          (item: { documentType: string | number; entityType: string | number }, index: string | number) => {
            entityList.value[index].documentType = documentTypeEnum.value[item.documentType];
            entityList.value[index].entityType = entityTypeEnum.value[item.entityType];
          },
        );
      }
      loading.close();
    })
    .catch(() => {
      loading.close();
    });
};
getEntityList();
</script>

<style scoped lang="scss">
.el-form--inline .el-form-item {
  margin-right: 10px;
  margin-bottom: 10px;
  width: 200px;
}
.el-select {
  :deep(.el-tag) {
    color: #fff;
    background-color: #419b62;
    .el-tag__close {
      color: #fff;
    }
  }
}
.container {
  .query {
    background-color: white;
    border-radius: 10px;
    padding: 20px 24px;
    &_row {
      display: flex;
      justify-content: space-between;
    }
    .picker_item {
      width: 35vw;
    }
    .query_reset {
      :deep(.el-form-item__content) {
        flex-wrap: nowrap;
      }
    }
  }
  .list {
    background-color: white;
    border-radius: 10px;
    margin-top: 24px;
    padding: 20px 24px;
    &_operate {
      margin-bottom: 14px;
      &_print {
        color: #419b62;
        border: 1px solid #419b62;
      }
      button {
        border-radius: 4px;
      }
    }
    .el-pagination {
      justify-content: center;
      margin-top: 10px;
    }
    &_status {
      display: flex;
      margin-bottom: 10px;
      align-items: center;
      &_pending {
        display: flex;
        margin-right: 8px;
        .list_status_pending_icon {
          width: 20px;
          height: 20px;
          border-radius: 10px;
          background-color: gray;
          margin-right: 4px;
        }
      }
      &_registered {
        display: flex;
        align-items: center;
        .list_status_registered_icon {
          width: 20px;
          height: 20px;
          border-radius: 10px;
          background-color: green;
          margin-right: 4px;
        }
      }
    }
  }
}
.registered_icon {
  width: 120px;
  height: 28px;
  border-radius: 4px;
  line-height: 28px;
  text-align: center;
  color: #419b62;
  background-color: #ecf5f0;
}
.pending_icon {
  width: 120px;
  height: 28px;
  text-align: center;
  line-height: 28px;
  border-radius: 4px;
  background-color: #e7ebea;
  color: #777;
}
</style>
